package com.ruoyi.subject.job;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.subject.service.IQbExamRecordService;
import com.ruoyi.subject.service.IQbSubjectService;
import com.ruoyi.subject.util.QbSubjectUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lzhj
 * @version 1.0.0
 * @className SubjectJob.java
 * @description
 * @date 2021年01月30日 14:35:00
 */
@Component
@EnableScheduling
public class SubjectTimer {

    private static Logger logger = LoggerFactory.getLogger(SubjectTimer.class);

    @Autowired
    private IQbExamRecordService qbExamRecordService;

    @Autowired
    private IQbSubjectService qbSubjectService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 每10分钟生成一次排名数据
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    private void createExamRecord() {
        Date date = new Date();
        try {
            logger.info("-----------生成成绩排名开始," + DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
            List<Map<String, Object>> recordList = qbExamRecordService.selectSorceRank();
            if (CollectionUtils.isNotEmpty(recordList)) {
                for (Map<String, Object> map : recordList) {
                    map.put("rank",map.get("rank1"));
                }
                //按题库类别放入缓存
                Map<String, List<Map<String, Object>>> sub_typeMap = recordList.stream().collect(Collectors.groupingBy(e -> (String) e.get("sub_type")));
                for (Map.Entry<String, List<Map<String, Object>>> entry : sub_typeMap.entrySet()) {
                    String subType = entry.getKey();
                    List<Map<String, Object>> records = entry.getValue();
                    redisCache.setCacheObject(QbSubjectUtil.getExamRecordCacheKey(subType), records);
                }

            }
            logger.info("-----------生成成绩排名结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("生成成绩排名的定时器异常," + DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
        }
    }

}
